package cn.edu.ctbu.websql.controller;

import cn.edu.ctbu.websql.domain.Result;
import cn.edu.ctbu.websql.domain.Student;
import cn.edu.ctbu.websql.helper.PageUtils;
import cn.edu.ctbu.websql.service.StudentServer;


import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@Slf4j
@RestController
@RequestMapping(value = "/webapi/students")
public class Controller {
    @Autowired
    private StudentServer studentServer;
    /**
     * 读取url：/webapi/students/list，显示学生列表
     * @return
     */
    @GetMapping("/list")
    public PageUtils GetAll(Integer limit, Integer page){
        Pageable pageable = PageRequest.of(page-1,limit);

        Page<Student> temStudent = studentServer.getAll(pageable);
        PageUtils pageUtils = new PageUtils(temStudent.getTotalElements(),temStudent.getContent());
        return  pageUtils;
    }
    /**
     * 新增插入学生的方法,url：/webapi/students/insert
     * @param student
     * @return
     */
    @PostMapping("/insert")
    public Student insert(@Valid Student student){
        return studentServer.Insert(student);
    }

    /**
     * 新增删除学生信息的方法，url:/webapi/students/delete
     * @param id
     */
    @DeleteMapping ("/delete/{id}")
    public void delete(@PathVariable Integer id){
        studentServer.delete(id);
    }

    /**
     * 新增更新学生数据内容，url：/webapi/students/updata
     * @param id
     * @return
     */
    @PutMapping("/update/{id}")
    public Student update(@PathVariable Integer id,@Valid Student newStudent){
        // 在方法参数上使用 @Valid 注解，触发实体类的验证
        Student updatedStudent = studentServer.update(id, newStudent);
        return updatedStudent;
    }
    @GetMapping("/getdata/{id}")
    public Optional<Student> getData(@PathVariable Integer id){
        return studentServer.getData(id);
    }
    @GetMapping("/search/{no}")
    public List<Student> searchData(@PathVariable String no){
        return studentServer.searchData(no);
    }

    @GetMapping("/list1")
    public Result GetAll(){
        List<Student> students = studentServer.findAll();
        Result result = new Result();
        result.setCode(200);
        result.setSuccess(true);
        result.setData(students);
        result.setMsg("学生列表信息");
        return result;
    }
}
